import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  BetaSchemaForm,
  FooterToolbar,
  GridContent,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Drawer, Dropdown, Form, Input, Modal, Popconfirm, message } from 'antd';
import React, { useRef, useState } from 'react';
import { addRole, addRolePermission, batchDelRole, batchDelRolePermission, getRolePage, getRolePermission, updateRole, updateRolePermission } from './service';
import { flushSync } from 'react-dom';

const handleRemove = async (idList: any[]) => {
  const hide = message.loading('正在删除');
  if (!idList) return true;

  try {
    const res = await batchDelRole({
      idList,
    });
    hide();
    if (res.code == 0) {
      message.success('删除成功，即将刷新');
      return true;
    } else {
      message.error('删除失败，请重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const [addForm] = Form.useForm()
  const [addPermissionForm] = Form.useForm()
  const [editPermissionForm] = Form.useForm()
  const [editForm] = Form.useForm()
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const roleActionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);

  const permissionColumns: ProColumns<any>[] = [
    {
      title: '权限名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [{ required: true }]
      }
    },
    {
      title: '权限编码',
      dataIndex: 'code',
      formItemProps: {
        rules: [{ required: true }]
      }
    },
    {
      title: '权限描述',
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record: any) => [
        <BetaSchemaForm<any>
          key="edit"
          layoutType="ModalForm"
          form={editPermissionForm}
          modalProps={{
            title: '编辑权限',
            width: 600,
          }}
          columns={permissionColumns as any}
          trigger={<a
            key="config"
            onClick={() => {
              editPermissionForm.setFieldsValue(record)
            }}
          >
            编辑
          </a>}
          onFinish={async (values) => {
            const hide = message.loading('正在保存');

            try {
              const res = await updateRolePermission({
                ...record,
                ...values,
                roleId: currentRow?.id,
                permissionId: record?.id
              });
              hide();
              if (res.code == 0) {
                message.success('保存成功');
                roleActionRef.current?.reload()
                return true;
              } else {
                message.error('保存失败请重试！');
                return false;
              }
            } catch (error) {
              hide();
              message.error('保存失败请重试！');
              return false;
            }
          }}
        />,
        <Popconfirm key='del' title="是否要删除此权限？" onConfirm={async () => {
          const hide = message.loading('正在删除');

            try {
              const res = await batchDelRolePermission({
                idList: [record?.id],
                roleId: currentRow?.id,
              });
              hide();
              if (res.code == 0) {
                message.success('删除成功');
                roleActionRef.current?.reload()
                return true;
              } else {
                return false;
              }
            } catch (error) {
              hide();
              message.error('保存失败请重试！');
              return false;
            }
        }}>
          <a onClick={() => {
          }}>删除</a>
        </Popconfirm>,
      ],
    },
  ]

  const columns: ProColumns<any>[] = [
    {
      title: '序号',
      valueType: 'indexBorder',
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          { required: true }
        ]
      }
    },
    {
      title: '角色编码',
      dataIndex: 'code',
      hideInSearch: true,
      formItemProps: {
        rules: [
          { required: true }
        ]
      }
    },
    {
      title: '角色描述',
      dataIndex: 'description',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record: any) => [
        <BetaSchemaForm<any>
          key="edit"
          layoutType="ModalForm"
          form={editForm}
          modalProps={{
            title: '编辑角色',
            width: 600,
          }}
          columns={columns as any}
          trigger={<a
            key="config"
            onClick={() => {
              editForm.setFieldsValue(record)
            }}
          >
            编辑
          </a>}
          onFinish={async (values) => {
            const hide = message.loading('正在保存');

            try {
              const res = await updateRole({
                ...record,
                ...values,
              });
              hide();
              if (res.code == 0) {
                message.success('保存成功');
                actionRef.current?.reload()
                return true;
              } else {
                message.error('保存失败请重试！');
                return false;
              }
            } catch (error) {
              hide();
              message.error('保存失败请重试！');
              return false;
            }
          }}
        />,
        <a key={'show'} onClick={() => {
          setCurrentRow(record)
          flushSync(() => {
            setShowDetail(true)
          })
        }}>查看角色权限</a>,
        <Popconfirm key='del' title="是否要删除此角色？" onConfirm={async () => {
          const res = await handleRemove([record?.id])
          if (res) {
            actionRef.current?.reload()
          }
          return res
        }}>
          <a onClick={() => {
          }}>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={{
        }}
        toolBarRender={() => [
          <BetaSchemaForm<any>
            key={'add'}
            layoutType="ModalForm"
            form={addForm}
            modalProps={{
              title: '新增角色',
              width: 600,
            }}
            columns={columns as any}
            trigger={<Button type='primary' onClick={() => {
              addForm.resetFields()
            }}
              icon={<PlusOutlined />}>新增</Button>}
            onFinish={async (values) => {
              const hide = message.loading('正在添加');

              try {
                const res = await addRole({ ...values });
                hide();
                if (res.code == 0) {
                  message.success('添加成功');
                  actionRef.current?.reload()
                  return true;
                } else {
                  message.error('添加失败请重试！');
                  return false;
                }

              } catch (error) {
                hide();
                message.error('添加失败请重试！');
                return false;
              }
            }}
          />,
        ]}
        request={async ({ current, pageSize, ...params }) => {
          const res = await getRolePage({
            current,
            pageSize,
            ...params
          })

          return {
            data: res?.data?.currentData || [],
            total: res?.data?.totalRecords
          }
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys: selectedRowsState.map((row: any) => row.id),
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >
          <Popconfirm key='del' title={`是否要批量删除 ${selectedRowsState.length} 条？`} onConfirm={async () => {
            const res = await handleRemove(selectedRowsState.map((row: any) => row.id));
            if (res) {
              actionRef.current?.reload()
              setSelectedRows([]);
            }
          }}>
            <Button danger>
              批量删除
            </Button>
          </Popconfirm>

        </FooterToolbar>
      )}

      <Modal
        width={1000}
        title={<>角色 <span style={{ color: '#9a1010', textDecoration: 'underline' }}>{currentRow?.name}</span> 的权限列表</>}
        open={showDetail}
        onCancel={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        footer={false}
        destroyOnClose
      >
        <ProTable<any>
          actionRef={roleActionRef}
          columns={permissionColumns}
          toolBarRender={() => [
            <BetaSchemaForm<any>
              key={'add'}
              layoutType="ModalForm"
              form={addPermissionForm}
              modalProps={{
                title: '新增权限',
                width: 600,
              }}
              columns={permissionColumns as any}
              trigger={<Button onClick={() => {
                addPermissionForm.resetFields()
              }}
                icon={<PlusOutlined />}>新增</Button>}
              onFinish={async (values) => {
                const hide = message.loading('正在添加');

                try {
                  const res = await addRolePermission({ 
                    ...values,
                    roleId: currentRow?.id,
                  });
                  hide();
                  if (res.code == 0) {
                    message.success('添加成功');
                    roleActionRef.current?.reload()
                    return true;
                  } else {
                    message.error('添加失败请重试！');
                    return false;
                  }

                } catch (error) {
                  hide();
                  message.error('添加失败请重试！');
                  return false;
                }
              }}
            />,
          ]}
          request={async ({ }) => {
            const res = await getRolePermission({
              roleId: currentRow?.id
            })
            return {
              data: res?.data?.permissionList || [],
            }
          }}
          pagination={false}
          rowKey="id"
          search={false}
          options={false}
          dateFormatter="string"
          headerTitle="角色权限"
        />
      </Modal>
    </PageContainer>
  );
};

export default TableList;
